package com.cyf.filmDownload.film.service.impl;

import com.cyf.filmDownload.common.threadPool.ExecutorUtil;
import com.cyf.filmDownload.common.threadPool.ThreadPoolConfig;
import com.cyf.filmDownload.film.entity.FilmDetail;
import com.cyf.filmDownload.film.entity.SearchResult;
import com.cyf.filmDownload.film.exception.FilmException;
import com.cyf.filmDownload.film.service.AbstractFilmService;
import com.cyf.filmDownload.m3u8.core.M3u8DownloadUtil;
import com.cyf.filmDownload.okhttp.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
public class NaiChaFilmService extends AbstractFilmService {

    public static final String WEBSITE_URL = "http://www.naicha86.com";

    public static final String SEARCH_URL = "http://www.naicha86.com/ysso/-------------.html?wd=";

    @Override
    public List<SearchResult> searchFilmInfo(String searchParam) {
        String html;
        try(Response response = HttpUtil.get("http://www.naicha86.com/ysso/-------------.html?wd=" + searchParam)) {
            html = response.body().string();
        } catch (IOException e) {
            throw new FilmException("获取电影页面异常", e);
        }
        Document document = Jsoup.parse(html);
        Elements ul = document.getElementsByClass("aec613 xxx TPostMv");
        List<SearchResult> resList = new ArrayList<>();
        List<Runnable> runnableList = new ArrayList<>();
        for (int i = 0; i < ul.size(); i++) {
            SearchResult res = new SearchResult();
            Element li = ul.get(i);
            String href = li.select("div > a").attr("href");
            String fileName = li.select("div > a > div > figure > img").attr("alt");
            res.setPageUrl(WEBSITE_URL + href);
            res.setFilmName(fileName);
            resList.add(res);
            runnableList.add(() -> getFilmDetail(res));
        }
        ExecutorUtil.syncExecute(ThreadPoolConfig.crawlerThreadPool, runnableList);
        return resList;
    }

    @Override
    public String getM3u8Url(String viweUrl) {
        String html;
        try(Response response = HttpUtil.get(viweUrl)) {
            html = response.body().string();
            String startStr = "},\"url\":\"";
            String endStr = "\",\"url_next\"";
            String m3u8Url = html.substring(html.indexOf(startStr) + startStr.length(), html.indexOf(endStr));
            m3u8Url = URLDecoder.decode(m3u8Url, "UTF-8");
            return m3u8Url;
        } catch (IOException e) {
            throw new FilmException("观看页面访问异常");
        }
    }

    public void getFilmDetail(SearchResult result) {
        String html;
        try(Response response = HttpUtil.get(result.getPageUrl())) {
            html = response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        List<FilmDetail> details = new ArrayList<>();
        Document document = Jsoup.parse(html);
        String actors = document.getElementsByClass("b95b18 tt-at").stream().map(Element::text).collect(Collectors.joining(","));
        String filmDesc = document.getElementsByClass("c44603 Description shrink-box").select("p > span").text();
        result.setActor(actors);
        result.setFilmDesc(filmDesc);

        // 获取剧集
        for (Element element : document.getElementsByClass("ewave-tab-content")) {
            Elements contentList = element.select("li");
            for (int i = 0; i < contentList.size(); i++) {
                Element content = contentList.get(i);
                String viewUri = content.select("li > a").attr("href");
                String desc = content.select("li > a").attr("title");
                FilmDetail detail = new FilmDetail();
                detail.setFilmIndex(i + 1);
                detail.setFileViewUrl(WEBSITE_URL + viewUri);
                detail.setDesc(desc);
                details.add(detail);
            }
        }
        result.setFilmDetails(details);
    }

}